package io.web.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.web.api.model.vo.InterfaceAnalysisVo;
import io.web.utils.ErrorCode;
import io.web.api.exception.ThrowUtils;
import io.web.api.mapper.UserInterfaceInfoMapper;
import io.web.api.model.entity.UserInterfaceInfo;
import io.web.api.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @description 针对表【user_interface_info(用户接口访问管理)】的数据库操作Service实现
 * @createDate 2023-05-28 13:54:47
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {

    @Resource
    UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Override
    public boolean updateTimes(Long userId, Long interfaceId) {
        ThrowUtils.throwIf(userId == null || interfaceId == null, ErrorCode.PARAMS_ERROR);

        UpdateWrapper<UserInterfaceInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("userId", userId);
        wrapper.eq("interfaceId", interfaceId);
        wrapper.setSql("totalTimes = totalTimes + 1, leftTimes = leftTimes - 1");
        return update(wrapper);
    }

    @Override
    public boolean checkTimes(Long interfaceId, Long userId) {
        QueryWrapper<UserInterfaceInfo> qw = new QueryWrapper<>();
        qw.eq("userId", userId);
        qw.eq("interfaceId", interfaceId);
        UserInterfaceInfo userInterfaceInfo = this.baseMapper.selectOne(qw);
        if (userInterfaceInfo == null) {
            // 没有则新建一条记录
            userInterfaceInfo = new UserInterfaceInfo();
            userInterfaceInfo.setUserId(userId);
            userInterfaceInfo.setInterfaceId(interfaceId);
            userInterfaceInfo.setTotalTimes(0);
            // 默认设置100
            userInterfaceInfo.setLeftTimes(100);
            this.baseMapper.insert(userInterfaceInfo);
        }
        return userInterfaceInfo.getLeftTimes() <= 0;
    }

    @Override
    public List<InterfaceAnalysisVo> interfaceAnalysis() {
        return userInterfaceInfoMapper.interfaceAnalysis();
    }

}




